package com.example.demo.four;

import javax.sound.sampled.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(2);

        CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() {
            @Override
            public void run() {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss");
                System.out.println("参赛选手准备就绪：比赛开始！" + sdf.format(System.currentTimeMillis()
                ));
            }
        });
        participant1 p1 = new participant1("选手1", 2, es, barrier);
        participant2 p2 = new participant2("选手2", 2, es, barrier);

        es.submit(p1);
        es.submit(p2);
        try {
            // 获取音频输入流
            AudioInputStream audioInputStream = AudioSystem
                    .getAudioInputStream(new File("F:\\作业区\\java实训\\thirdly\\src\\main\\java\\com\\example\\demo\\music\\刘欢、Sarah Brightman - 我和你.wav"));
            // 获取音频编码对象
            AudioFormat audioFormat = audioInputStream.getFormat();

            // 设置数据输入
            DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class,
                    audioFormat, AudioSystem.NOT_SPECIFIED);
            SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem
                    .getLine(dataLineInfo);
            sourceDataLine.open(audioFormat);
            sourceDataLine.start();

            /*
             * 从输入流中读取数据发送到混音器
             */
            int count;
            byte tempBuffer[] = new byte[1024];
            while ((count = audioInputStream.read(tempBuffer, 0, tempBuffer.length)) != -1) {
                if (count > 0) {
                    sourceDataLine.write(tempBuffer, 0, count);
                }
            }

            // 清空数据缓冲,并关闭输入
            sourceDataLine.drain();
            sourceDataLine.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        es.shutdown();
    }
}
